#客户端
import aiohttp
import asyncio
import json
import _plot
import os
import _initfile


async def fetch(client,data):
    #合并文件
    if os.path.exists('merge.dat') == False:
        _initfile.mergeFile()
    url = f'http://127.0.0.1:8000/?'
    query_json = "query="
    #转换查询数据为字符串
    data_str = json.dumps(data)
    query_json += data_str
    url += query_json
    #查询
    async with client.get(url) as resp:
        assert resp.status == 200
        return await resp.json()

async def main():
    async with aiohttp.ClientSession() as client:
        #默认数据
        # data = {
        #     "type":"Polygon",
        #     "coordinates":[[30.0,10.0],[40.0,40.0],[20.0,40.0],[10.0,20.0],[30.0,10.0]]
        # }
        #数据1 没有人口
        # data = {
        #     "type":"Polygon",
        #     "coordinates":[[10.1,10.2],[11.1,11.2],[11.1,10.3],[10.1,10.2]]
        # }
        # data = {
        #     "type":"Polygon",
        #     "coordinates":[[116.1,60.2],[117.3,61.8],[119.1,60.2],[116.1,60.2]]
        # }
        data = {
            "type":"Polygon",
            "coordinates":[[116.1,60.2],[120.3,65.8],[123.1,60.2],[116.1,60.2]]
        }
        #获取用户输入的凸多边形数据
        sideNum = input("请输入查询多边形边数:")
        if int(sideNum) > 0:
            data["coordinates"].clear()
            for i in range(int(sideNum)+1):
                print(f'请输入第{i+1}个坐标')
                coordinate_x = input('X:')
                coordinate_y = input('y:')
                data["coordinates"].append([float(coordinate_x),float(coordinate_y)]) 
        #发起查询
        ret = await fetch(client,data)
        print(f'type:{type(ret)}')
        retList = json.loads(ret)
        print(f'retList type:{type(retList)} len:{len(retList)}')
        _plot.plotPolygonal(data,retList)

loop = asyncio.get_event_loop()

loop.run_until_complete(main())